package initialize

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"log"
	"sheep_script/global"
	"sheep_script/utils"
)

func InitConfig() *viper.Viper {

	v := viper.New()
	v.SetConfigType("yaml")
	//// 设置配置文件路径
	v.SetConfigFile(utils.GetRootContents() + "/config.yaml")

	// 读取配置文件
	err := v.ReadInConfig()
	if err != nil {
		log.Fatalf("Error reading config file, %s", err)
	}

	v.WatchConfig()

	v.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("config file changed:", e.Name)
		if err = v.Unmarshal(&global.Config); err != nil {
			fmt.Println(err)
		}
	})

	if err = v.Unmarshal(&global.Config); err != nil {
		fmt.Println(err)
	}

	return v
}
